/*
========================================================================
 Name        : SingaporeBusAccessPointsPriorityListBoxView.cpp
 Author      : 
 Copyright   : Your copyright notice
 Description : 
========================================================================
*/
// [[[ begin generated region: do not modify [Generated System Includes]
#include <aknviewappui.h>
#include <eikmenub.h>
#include <avkon.hrh>
#include <barsread.h>
#include <stringloader.h>
#include <eikenv.h>
#include <akniconarray.h>
#include <eikclbd.h>
#include <akncontext.h>
#include <akntitle.h>
#include <eikbtgpc.h>
#include <SingaporeBus.rsg>
// ]]] end generated region [Generated System Includes]

// [[[ begin generated region: do not modify [Generated User Includes]

#include "SingaporeBus.hrh"
#include "SingaporeBusAccessPointsPriorityListBoxView.h"
#include "PublicTransportMapContainer.hrh"
#include "SingaporeBusSettingItemList.hrh"
#include "SingaporeBusAccessPointsPriorityListBox.hrh"
#include "SingaporeBusAccessPointsPriorityListBox.h"
// ]]] end generated region [Generated User Includes]

#include <aknlists.h>		// CAknSinglePopupMenuStyleListBox
#include <CommDbConnPref.h>
#include <CommDb.h>		// CCommsDatabase
#include <aknpopup.h>
#include <S32FILE.H>

#include "SingaporeBusDocument.h"

// [[[ begin generated region: do not modify [Generated Constants]
// ]]] end generated region [Generated Constants]

/**
 * First phase of Symbian two-phase construction. Should not contain any
 * code that could leave.
 */
CSingaporeBusAccessPointsPriorityListBoxView::CSingaporeBusAccessPointsPriorityListBoxView()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	iSingaporeBusAccessPointsPriorityListBox = NULL;
	// ]]] end generated region [Generated Contents]
	
	}

/** 
 * The view's destructor removes the container from the control
 * stack and destroys it.
 */
CSingaporeBusAccessPointsPriorityListBoxView::~CSingaporeBusAccessPointsPriorityListBoxView()
	{
	// [[[ begin generated region: do not modify [Generated Contents]
	delete iSingaporeBusAccessPointsPriorityListBox;
	iSingaporeBusAccessPointsPriorityListBox = NULL;
	// ]]] end generated region [Generated Contents]
	
	for(TInt i = 0 ; i < iListBoxItemInfo.Count() ; ++i)
		iListBoxItemInfo[i].Close();
	iListBoxItemInfo.Close();
	iItemText.Close();
	
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance then calls the second-phase constructor
 * without leaving the instance on the cleanup stack.
 * @return new instance of CSingaporeBusAccessPointsPriorityListBoxView
 */
CSingaporeBusAccessPointsPriorityListBoxView* CSingaporeBusAccessPointsPriorityListBoxView::NewL()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CSingaporeBusAccessPointsPriorityListBoxView* self = CSingaporeBusAccessPointsPriorityListBoxView::NewLC();
	CleanupStack::Pop( self );
	return self;
	}

/**
 * Symbian two-phase constructor.
 * This creates an instance, pushes it on the cleanup stack,
 * then calls the second-phase constructor.
 * @return new instance of CSingaporeBusAccessPointsPriorityListBoxView
 */
CSingaporeBusAccessPointsPriorityListBoxView* CSingaporeBusAccessPointsPriorityListBoxView::NewLC()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CSingaporeBusAccessPointsPriorityListBoxView* self = new ( ELeave ) CSingaporeBusAccessPointsPriorityListBoxView();
	CleanupStack::PushL( self );
	self->ConstructL();
	return self;
	}


/**
 * Second-phase constructor for view.  
 * Initialize contents from resource.
 */ 
void CSingaporeBusAccessPointsPriorityListBoxView::ConstructL()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// [[[ begin generated region: do not modify [Generated Code]
	BaseConstructL( R_SINGAPORE_BUS_ACCESS_POINTS_PRIORITY_LIST_BOX_SINGAPORE_BUS_ACCESS_POINTS_PRIORITY_LIST_BOX_VIEW );
				
	// ]]] end generated region [Generated Code]
	
	// add your own initialization code here
	iItemText.CreateL(256);
	}

/**
 * @return The UID for this view
 */
TUid CSingaporeBusAccessPointsPriorityListBoxView::Id() const
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	return TUid::Uid( ESingaporeBusAccessPointsPriorityListBoxViewId );
	// [[[ begin generated region: do not modify [Generated Code]
	// ]]] end generated region [Generated Code]
	
	}

/**
 * Handle a command for this view (override)
 * @param aCommand command id to be handled
 */
void CSingaporeBusAccessPointsPriorityListBoxView::HandleCommandL( TInt aCommand )
	{
	// [[[ begin generated region: do not modify [Generated Code]
	TBool commandHandled = EFalse;
	switch ( aCommand )
		{	// code to dispatch to the AknView's menu and CBA commands is generated here
	
		case EAknSoftkeyDone:
			commandHandled = HandleControlPaneRightSoftKeyPressedL( aCommand );
			break;
		case ESingaporeBusAccessPointsPriorityListBoxViewInsertMenuItemCommand:
			commandHandled = HandleInsertMenuItemSelectedL( aCommand );
			break;
		case ESingaporeBusAccessPointsPriorityListBoxViewAppendMenuItemCommand:
			commandHandled = HandleAppendMenuItemSelectedL( aCommand );
			break;
		case ESingaporeBusAccessPointsPriorityListBoxViewRemoveMenuItemCommand:
			commandHandled = HandleRemoveMenuItemSelectedL( aCommand );
			break;
		default:
			break;
		}
	
		
	if ( !commandHandled ) 
		{
	
		if ( aCommand == EAknSoftkeyDone )
			{
			AppUi()->HandleCommandL( EEikCmdExit );
			}
	
		}
	// ]]] end generated region [Generated Code]
	
	}

void CSingaporeBusAccessPointsPriorityListBoxView::SetAccessPoints(const RArray<TUint32>& aPriorityList)
	{	
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CCommsDatabase* commDB = CCommsDatabase::NewL();
	CleanupStack::PushL(commDB); // Open the IAP table
	_LIT(kUnknonwIap, "<Unknown>");
	for(TInt i = 0 ; i < iListBoxItemInfo.Count() ; ++i)
		iListBoxItemInfo[i].Close();
	iListBoxItemInfo.Reset();
	for(int i = 0 ; i < aPriorityList.Count() ; ++i)
		{
		RListBoxItemInfo listBoxItem;
		listBoxItem.iIap = aPriorityList[i];
		CCommsDbTableView* view = commDB->OpenViewMatchingUintLC(TPtrC(IAP), TPtrC(COMMDB_ID), listBoxItem.iIap);
		TBuf<128> buf;
		if (view->GotoFirstRecord() == KErrNone)
			{
			view->ReadTextL(TPtrC(COMMDB_NAME), buf);
			listBoxItem.iName = buf.AllocL();
			}
		else 
			listBoxItem.iName = kUnknonwIap().AllocL();
		CleanupStack::PopAndDestroy(); // view
		iListBoxItemInfo.AppendL(listBoxItem);
		}
	iSingaporeBusAccessPointsPriorityListBox->ListBox()->HandleItemAdditionL();
	CleanupStack::PopAndDestroy(); // commDB	
	}


/**
 *	Handles user actions during activation of the view, 
 *	such as initializing the content.
 */
void CSingaporeBusAccessPointsPriorityListBoxView::DoActivateL( 
		const TVwsViewId& aPrevViewId,
		TUid /*aCustomMessageId*/,
		const TDesC8& /*aCustomMessage*/ )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// [[[ begin generated region: do not modify [Generated Contents]
	SetupStatusPaneL();
	
				
	if ( iSingaporeBusAccessPointsPriorityListBox == NULL )
		{
		iSingaporeBusAccessPointsPriorityListBox = CreateContainerL();
		iSingaporeBusAccessPointsPriorityListBox->SetMopParent( this );
		AppUi()->AddToStackL( *this, iSingaporeBusAccessPointsPriorityListBox );
		} 
	// ]]] end generated region [Generated Contents]
	
	// [[[ begin generated region: do not modify [Generated Code]
	// ]]] end generated region [Generated Code]
	
	iPrevViewId = aPrevViewId;
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	SetAccessPoints(doc->iIapPriorityList);
	
	}

/**
 */
void CSingaporeBusAccessPointsPriorityListBoxView::DoDeactivate()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// [[[ begin generated region: do not modify [Generated Contents]
	CleanupStatusPane();
	
	if ( iSingaporeBusAccessPointsPriorityListBox != NULL )
		{
		AppUi()->RemoveFromViewStack( *this, iSingaporeBusAccessPointsPriorityListBox );
		delete iSingaporeBusAccessPointsPriorityListBox;
		iSingaporeBusAccessPointsPriorityListBox = NULL;
		}
	// ]]] end generated region [Generated Contents]
	
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	
	
	}

/** 
 * Handle status pane size change for this view (override)
 */
void CSingaporeBusAccessPointsPriorityListBoxView::HandleStatusPaneSizeChange()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	CAknView::HandleStatusPaneSizeChange();
	
	// this may fail, but we're not able to propagate exceptions here
	TVwsViewId view;
	AppUi()->GetActiveViewId( view );
	if ( view.iViewUid == Id() )
		{
		TInt result;
		TRAP( result, SetupStatusPaneL() );
		}
	
	// [[[ begin generated region: do not modify [Generated Code]
	// ]]] end generated region [Generated Code]
	
	// [[[ begin generated region: do not modify [Generated Contents]
	// ]]] end generated region [Generated Contents]
	
	}

// [[[ begin generated function: do not modify
void CSingaporeBusAccessPointsPriorityListBoxView::SetupStatusPaneL()
	{
	// reset the context pane
	TUid contextPaneUid = TUid::Uid( EEikStatusPaneUidContext );
	CEikStatusPaneBase::TPaneCapabilities subPaneContext = 
		StatusPane()->PaneCapabilities( contextPaneUid );
	if ( subPaneContext.IsPresent() && subPaneContext.IsAppOwned() )
		{
		CAknContextPane* context = static_cast< CAknContextPane* > ( 
			StatusPane()->ControlL( contextPaneUid ) );
		context->SetPictureToDefaultL();
		}
	
	// setup the title pane
	TUid titlePaneUid = TUid::Uid( EEikStatusPaneUidTitle );
	CEikStatusPaneBase::TPaneCapabilities subPaneTitle = 
		StatusPane()->PaneCapabilities( titlePaneUid );
	if ( subPaneTitle.IsPresent() && subPaneTitle.IsAppOwned() )
		{
		CAknTitlePane* title = static_cast< CAknTitlePane* >( 
			StatusPane()->ControlL( titlePaneUid ) );
		TResourceReader reader;
		iEikonEnv->CreateResourceReaderLC( reader, R_SINGAPORE_BUS_ACCESS_POINTS_PRIORITY_LIST_BOX_TITLE_RESOURCE );
		title->SetFromResourceL( reader );
		CleanupStack::PopAndDestroy(); // reader internal state
		}
				
	}

// ]]] end generated function

// [[[ begin generated function: do not modify
void CSingaporeBusAccessPointsPriorityListBoxView::CleanupStatusPane()
	{
	}

// ]]] end generated function




TInt CSingaporeBusAccessPointsPriorityListBoxView::MdcaCount() const
{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	return iListBoxItemInfo.Count();
}

TPtrC16 CSingaporeBusAccessPointsPriorityListBoxView::MdcaPoint(TInt aIndex) const
{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	iSingaporeBusAccessPointsPriorityListBox->CreateListBoxItemL(iItemText, aIndex + 1, aIndex >= iListBoxItemInfo.Count() ? KNullDesC() : *iListBoxItemInfo[aIndex].iName);
	return iItemText;
}

/**
 *	Creates the top-level container for the view.  You may modify this method's
 *	contents and the CIApPriorityListbox::NewL() signature as needed to initialize the
 *	container, but the signature for this method is fixed.
 *	@return new initialized instance of CIApPriorityListbox
 */
CSingaporeBusAccessPointsPriorityListBox* CSingaporeBusAccessPointsPriorityListBoxView::CreateContainerL()
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	return CSingaporeBusAccessPointsPriorityListBox::NewL( ClientRect(), NULL, this );
	}

//http://wiki.forum.nokia.com/index.php/Reading_internet_access_points_from_the_device
struct TIapData
	{
	TBuf<128> iName;
	TUint32 iIap;
	};
static TInt SelectIAPL(TIapData& aRet);


/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusAccessPointsPriorityListBoxView::HandleInsertMenuItemSelectedL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// TODO: implement selected event handler
	TIapData selectedIap;
	if(SelectIAPL(selectedIap))
		{
		RListBoxItemInfo listBoxItemInfo;
		listBoxItemInfo.iName = selectedIap.iName.AllocLC();
		listBoxItemInfo.iIap = selectedIap.iIap;
		iListBoxItemInfo.InsertL(
				listBoxItemInfo,
				Max(0,iSingaporeBusAccessPointsPriorityListBox->ListBox()->CurrentItemIndex())
				);
		CleanupStack::Pop(); // selectedIap.iName.AllocLC()
		iSingaporeBusAccessPointsPriorityListBox->ListBox()->HandleItemAdditionL();
		}
	return ETrue;
	}
				

				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusAccessPointsPriorityListBoxView::HandleRemoveMenuItemSelectedL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// TODO: implement selected event handler
	if(iSingaporeBusAccessPointsPriorityListBox->ListBox()->CurrentItemIndex() != KErrNotFound)
		{
		iListBoxItemInfo[iSingaporeBusAccessPointsPriorityListBox->ListBox()->CurrentItemIndex()].Close();
		iListBoxItemInfo.Remove(iSingaporeBusAccessPointsPriorityListBox->ListBox()->CurrentItemIndex());
		iSingaporeBusAccessPointsPriorityListBox->ListBox()->HandleItemRemovalL();
		}
	return ETrue;
	}


static TInt SelectIAPL(TIapData& aRet)
	{
	CArrayFixFlat<TIapData>* iEApList=new (ELeave) CArrayFixFlat<TIapData>(2) ;
	TInt stack=0;
	// Make listitems. and PUSH it
	CAknSinglePopupMenuStyleListBox* list = new(ELeave) CAknSinglePopupMenuStyleListBox;
	CleanupStack::PushL(list);
	stack++;
  	// Create popup list and PUSH it.
	CAknPopupList* popupList = CAknPopupList::NewL(list, R_AVKON_SOFTKEYS_OK_CANCEL, AknPopupLayouts::EMenuWindow);
	CleanupStack::PushL(popupList);
	stack++;
  	CDesCArrayFlat* items = new (ELeave) CDesCArrayFlat(5);
	CleanupStack::PushL(items);
	stack++;
 	// initialize listbox.
	list->ConstructL(popupList, CEikListBox::ELeftDownInViewRect);
	list->CreateScrollBarFrameL(ETrue);
	list->ScrollBarFrame()->SetScrollBarVisibilityL(CEikScrollBarFrame::EOff, CEikScrollBarFrame::EAuto);
  	TBuf<52> iapfromtable;
	TInt err = KErrNone;
 	CCommsDatabase* iCommsDB=CCommsDatabase::NewL(EDatabaseTypeIAP);
	CleanupStack::PushL(iCommsDB);
	stack++;
 #ifdef __SERIES60_3X__
	CCommsDbTableView* gprsTable = iCommsDB->OpenIAPTableViewMatchingBearerSetLC(ECommDbBearerGPRS|ECommDbBearerWLAN|ECommDbBearerVirtual,ECommDbConnectionDirectionOutgoing);
 #else
	CCommsDbTableView* gprsTable = iCommsDB->OpenIAPTableViewMatchingBearerSetLC(ECommDbBearerGPRS|ECommDbBearerVirtual,		ECommDbConnectionDirectionOutgoing);
 #endif
	User::LeaveIfError(gprsTable->GotoFirstRecord());
	TInt i=0;
	TUint32 id;
	TIapData eap;
	TInt cur =0;
	//current value
	do
		{
		gprsTable->ReadTextL(TPtrC(COMMDB_NAME), iapfromtable);
		gprsTable->ReadUintL(TPtrC(COMMDB_ID), id);
		items->AppendL(iapfromtable);
		eap.iIap = id;
		eap.iName.Copy(iapfromtable);
		iEApList->AppendL(eap);
		err = gprsTable->GotoNextRecord();
		i++;
		}
	while (err == KErrNone);
	CleanupStack::PopAndDestroy(2);
	stack--;
  	// Set listitems.
	CTextListBoxModel* model = list->Model();
	model->SetItemTextArray(items);
	model->SetOwnershipType(ELbmOwnsItemArray);
	CleanupStack::Pop();
    popupList->SetTitleL(_L("IAP"));
	list->SetListBoxObserver(popupList);
	TInt popupOk = popupList->ExecuteLD();
	CleanupStack::Pop();
	TInt iap=0;
	if (popupOk)
		{
		TInt index = list->CurrentItemIndex();
		aRet = (*iEApList)[index];
		iap=(*iEApList)[index].iIap;
 	}
	CleanupStack::PopAndDestroy();
  	iEApList->Reset();
	delete iEApList;
	return iap;
}


/** 
 * Handle the rightSoftKeyPressed event.
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusAccessPointsPriorityListBoxView::HandleControlPaneRightSoftKeyPressedL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// TODO: implement rightSoftKeyPressed event handler
	
	CSingaporeBusDocument* doc = (CSingaporeBusDocument*)CEikonEnv::Static()->EikAppUi()->Document();
	doc->iIapPriorityList.Reset();
	for(TInt i = 0 ; i < iListBoxItemInfo.Count() ; ++i)
		doc->iIapPriorityList.AppendL(iListBoxItemInfo[i].iIap);
		
	static_cast<CAknViewAppUi*>(CEikonEnv::Static()->AppUi())->ActivateLocalViewL(
			iPrevViewId.iViewUid
		);
	return ETrue;
	}
				
/** 
 * Handle the selected event.
 * @param aCommand the command id invoked
 * @return ETrue if the command was handled, EFalse if not
 */
TBool CSingaporeBusAccessPointsPriorityListBoxView::HandleAppendMenuItemSelectedL( TInt aCommand )
	{
TFunTrace funTrace(__PRETTY_FUNCTION__);
	// TODO: implement selected event handler
	TIapData selectedIap;
	if(SelectIAPL(selectedIap))
		{
		RListBoxItemInfo listBoxItemInfo;
		listBoxItemInfo.iIap = selectedIap.iIap;
		listBoxItemInfo.iName = selectedIap.iName.AllocLC();
		iListBoxItemInfo.AppendL(
				listBoxItemInfo
				);
		CleanupStack::Pop(); // selectedIap.iName.AllocLC()
		iSingaporeBusAccessPointsPriorityListBox->ListBox()->HandleItemAdditionL();
		}
	return ETrue;
	}
				
